﻿using Core;
using Main;

public class InventoryWidget:FGUIWidget<UI_Inventory>
{
    private InventoryComponent inventoryComponent;
    private ListAdapter<UI_ItemSlot> listAdapter;

    protected override void OnInitialize(params object[] args)
    {
        inventoryComponent = Player.Instance.GetParent<Unit>().GetComponent<InventoryComponent>();
        UpdateList();

    }

    public void UpdateList()
    {
        ItemContainer itemContainer = inventoryComponent.backpack;
        listAdapter = new ListAdapter<UI_ItemSlot>(m_root.m_list);
        listAdapter.SetItemRenderer((index, component) =>
        {
            var slot = itemContainer[index];
            component.m_count.text = slot.count > 1 ? $"{slot.count}" : string.Empty;
            var config = World.GetComponent<ConfigComponent>().GetConfig<ItemConfig>(slot.itemId);
            component.m_icon.url = config?.icon;
        });

        listAdapter.SetClick((index, component) =>
        {
            var slot = itemContainer[index];

            //if (inventoryComponent.CurSlot != null)
            //{
            //    var selectComponent = listAdapter.GetChild(inventoryComponent.CurSlot.index);
            //    selectComponent.m_select.visible = false;
            //}

            if (inventoryComponent.CurSlot == null)
            {
                inventoryComponent.ChangeCurrentItemSlot(slot);
            }
            else if (inventoryComponent.CurSlot.IsEmpty)
            {
                inventoryComponent.ChangeCurrentItemSlot(inventoryComponent.CurSlot != slot ? slot : null);
            }
            else
            {
                inventoryComponent.Swap(inventoryComponent.CurSlot, slot);
                inventoryComponent.ChangeCurrentItemSlot(null);
            }
            //component.m_select.visible = inventoryComponent.CurSlot != null;
        });

        listAdapter.SetTouchBegin((index, component, _) =>
        {
            World.GetComponent<EventComponent>().Publish(new TouchBeginItemSlot { slot = itemContainer[index], component = component });
        });

        listAdapter.SetTouchEnd((index, component, _) =>
        {
            World.GetComponent<EventComponent>().Publish(new TouchEndItemSlot { slot = itemContainer[index], component = component });
        });

        listAdapter.SetLongPress((index, component) => { });

        listAdapter.UpdateCount(itemContainer.Count);
    }

    public void UpdateIndex(int index)
    {
        listAdapter.UpdateIndex(index);
    }

    public void SelectSlot(int index, bool isSelect)
    {
        var selectComponent = listAdapter.GetChild(index);
        selectComponent.m_select.visible = isSelect;
    }
}
